define(['jquery', 'bootstrap', 'utilback', 'addtabs', 'adminlte', 'form'], function ($, undefined, UtilBack, undefined, AdminLTE, Form) {
    var Controller = {
    	config: {
    		menu_url: '/user/read/promission',
    	},
    	init: function () {
    		$(document).on('click', 'a.logout', function() {
    			Layer.confirm('确定注销登录？', {title: '确认操作'}, function() {
        			Util.api.ajax({
    	                url: '/logout',
    	                type: 'post',
        			}, function (ret) {
        				location.href='/login.html';
        			});
    			});
    		});
    		Controller.initMenu(Controller.initStyle);
    	},
    	initMenu: function (initStyle) {
    		window.globalTitle = ' - 柠檬智慧社区管理平台';
            // 菜单
    		Util.api.ajax({
	                url: Controller.config.menu_url,
	                type: 'get',
    			}, function (ret) {
    				$('img.avatar').attr('src', ret.user.avatar);
    				$('.user-menu span,.user-info p a').text(ret.user.userName);
    				$('.user-header p').html(ret.user.userName + '<small></small>');
                	var html = '';
                    $.each(ret.menus, function (i, m) {
                    	if(m.request && m.request != '#') {
                    		html += '<li><a href="javascript:;" addtabs="'+m.id+'" url="'+m.request
                    		+'" py="'+m.py+'" pinyin="'+m.pinyin+'"><i class="'+m.iconcls+'"></i> <span>'+m.menuName
                    		+'</span> <span class="pull-right-container"></span></a> </li>';
                    	} else {
                    		html += '<li class=" treeview"><a href="javascript:;" addtabs="'+m.id
                    		+'" url="javascript:;" py="'+m.py+'" pinyin="'+m.pinyin+'"><i class="'+m.iconcls+'"></i> <span>'+m.menuName
                    		+'</span> <span class="pull-right-container"><i class="fa fa-angle-left pull-right"></i></span></a>'
                    		+'<ul class="treeview-menu">';
                        	$.each(m.menuBeans, function (j, mm) {
                        		html += '<li><a href="javascript:;" addtabs="'+mm.id+'" url="'+mm.request
                        		+'" py="'+mm.py+'" pinyin="'+mm.pinyin+'"><i class="'+mm.iconcls+'"></i> <span>'+mm.menuName
                        		+'</span> <span class="pull-right-container"></span></a> </li>';
                        	});
                        	html += '</ul></li>';
                    	}
                    });
                    $('.sidebar-menu').html(html);
                    initStyle();
            		
    	    		setInterval(show_cur_times, 100);
                }, initStyle);
	
	            function show_cur_times() {
	            	if($(".user-info small").length && $('.user-menu .dropdown-menu').is(':visible')) {
	    	            //获取当前日期
	    	            var date_time = new Date();
	    	            //定义星期
	    	            var week;
	    	            //switch判断
	    	            switch (date_time.getDay()) {
	    	                case 1:
	    	                    week = "星期一";
	    	                    break;
	    	                case 2:
	    	                    week = "星期二";
	    	                    break;
	    	                case 3:
	    	                    week = "星期三";
	    	                    break;
	    	                case 4:
	    	                    week = "星期四";
	    	                    break;
	    	                case 5:
	    	                    week = "星期五";
	    	                    break;
	    	                case 6:
	    	                    week = "星期六";
	    	                    break;
	    	                default:
	    	                    week = "星期天";
	    	                    break;
	    	            }
	    	
	    	            //年
	    	            var year = date_time.getFullYear();
	    	            //判断小于10，前面补0
	    	            if (year < 10) {
	    	                year = "0" + year;
	    	            }
	    	
	    	            //月
	    	            var month = date_time.getMonth() + 1;
	    	            //判断小于10，前面补0
	    	            if (month < 10) {
	    	                month = "0" + month;
	    	            }
	    	
	    	            //日
	    	            var day = date_time.getDate();
	    	            //判断小于10，前面补0
	    	            if (day < 10) {
	    	                day = "0" + day;
	    	            }
	    	
	    	            //时
	    	            var hours = date_time.getHours();
	    	            //判断小于10，前面补0
	    	            if (hours < 10) {
	    	                hours = "0" + hours;
	    	            }
	    	
	    	            //分
	    	            var minutes = date_time.getMinutes();
	    	            //判断小于10，前面补0
	    	            if (minutes < 10) {
	    	                minutes = "0" + minutes;
	    	            }
	    	
	    	            //秒
	    	            var seconds = date_time.getSeconds();
	    	            //判断小于10，前面补0
	    	            if (seconds < 10) {
	    	                seconds = "0" + seconds;
	    	            }
	    	
	    	            //拼接年月日时分秒
	    	            var date_str = year + "年" + month + "月" + day + "日 " + hours + ":" + minutes + ":" + seconds + '<br>' + week;
	    	
	    	            //显示在id为showtimes的容器里
	    	           $(".user-info small").html(date_str);
	            	}
	        	}
            //读取iBase4J的更新信息
            /*$.ajax({
                url: '#',
                type: 'post',
                dataType: 'jsonp',
                success: function (ret) {
                    $(".notifications-menu > a span").text(ret.new > 0 ? ret.new : '');
                    $(".notifications-menu .footer a").attr("href", ret.url);
                    $.each(ret.newslist, function (i, j) {
                        var item = '<li><a href="' + j.url + '" target="_blank"><i class="' + j.icon + '"></i> ' + j.title + '</a></li>';
                        $(item).appendTo($(".notifications-menu ul.menu"));
                    });
                }
            });*/

            // 信息
            /*$.ajax({
                url: '#',
                type: 'get',
                dataType: 'jsonp',
                success: function (ret) {
                	$.each(ret.data, function (i, j) {
                        var author = j.author ? j.author : {html_url: "https://github.com/karsonzhang", avatar_url: "/assets/img/avatar.png", login: "Anonymous"};
                        var item = '<li><a href="' + j.html_url + '"><div class="pull-left"><img src="' + author.avatar_url + '" class="img-circle" alt="' + author.login + '"></div><h4>' + author.login + '<small><i class="fa fa-clock-o"></i> ' + dateDiff(new Date(j.commit.committer.date).getTime()) + '</small></h4><p>' + j.commit.message + '</p></a></li>';
                        $(item).appendTo($(".github-commits ul.menu"));
                    });
                }
            });*/
        },
        initStyle: function() {
            //窗口大小改变,修正主窗体最小高度
            $(window).resize(function () {
                $(".tab-addtabs").css("height", $(".content-wrapper").height() + "px");
            });

            //双击重新加载页面
            $(document).on("dblclick", ".sidebar-menu li > a", function (e) {
                $("#tab_" + $(this).attr("addtabs") + " iframe").attr('src', function (i, val) {
                    return val;
                });
                e.stopPropagation();
            });
    		
            //快捷搜索
            var isAndroid = /(android)/i.test(navigator.userAgent);
            var searchResult = $(".menuresult");
            $("form.sidebar-form").on('click', '.menuresult a[data-url]', function () {
                UtilBack.api.addtabs($(this).data("url"));
            }).on("blur", "input[name=sq]", function () {
            	searchResult.fadeOut();
                if (isAndroid) {
                    $.AdminLTE.options.sidebarSlimScroll = true;
                }
            }).on("focus", "input[name=sq]", function () {
                if (isAndroid) {
                    $.AdminLTE.options.sidebarSlimScroll = false;
                }
                if ($("a", searchResult).size() > 0) {
                    searchResult.show();
                }
            }).on("keyup", "input[name=sq]", function () {
                searchResult.html('');
                var val = $(this).val();
                var html = new Array();
                if (val != '') {
                    $("ul.sidebar-menu li a[addtabs]:not([url^='javascript:;'])").each(function () {
                        if ($("span:first", this).text().indexOf(val) > -1 || $(this).attr("py").indexOf(val) > -1 || $(this).attr("pinyin").indexOf(val) > -1) {
                            html.push('<a data-url="' + $(this).attr("url") + '" url="javascript:;" href="javascript:;" addtabs="'+$(this).attr("addtabs")+'">' + $("span:first", this).text() + '</a>');
                            if (html.length >= 100) {
                                return false;
                            }
                        }
                    });
                }
                $(searchResult).append(html.join(""));
                if (html.length > 0) {
                    searchResult.removeClass('hide');
                    searchResult.show();
                } else {
                    searchResult.hide();
                }
            });
            
            //清除缓存
            $(document).on('click', "[data-toggle='wipecache']", function () {
                $.ajax({
                    url: 'app/flushcache',
                    dataType: 'json',
                    cache: false,
                    success: function (ret) {
                        if (ret.hasOwnProperty("code")) {
                            var msg = ret.hasOwnProperty("msg") && ret.msg != "" ? ret.msg : "";
                            if (ret.code === 1) {
                                Toastr.success(msg ? msg : __('Wipe cache completed'));
                            } else {
                                Toastr.error(msg ? msg : __('Wipe cache failed'));
                            }
                        } else {
                            Toastr.error(__('Unknown data format'));
                        }
                    }, error: function () {
                        Toastr.error(__('Network error'));
                    }
                });
            });

            //全屏事件
            $(document).on('click', "[data-toggle='fullscreen']", function () {
                var doc = document.documentElement;
                if ($(document.body).hasClass("full-screen")) {
                    $(document.body).removeClass("full-screen");
                    document.exitFullscreen ? document.exitFullscreen() : document.mozCancelFullScreen ? document.mozCancelFullScreen() : document.webkitExitFullscreen && document.webkitExitFullscreen();
                } else {
                    $(document.body).addClass("full-screen");
                    doc.requestFullscreen ? doc.requestFullscreen() : doc.mozRequestFullScreen ? doc.mozRequestFullScreen() : doc.webkitRequestFullscreen ? doc.webkitRequestFullscreen() : doc.msRequestFullscreen && doc.msRequestFullscreen();
                }
            });

            //绑定tabs事件
            $('#nav').addtabs({iframeHeight: "100%"});

            //修复iOS下iframe无法滚动的BUG
            if (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) {
                $(".tab-addtabs").addClass("ios-iframe-fix");
            }

            if ($("ul.sidebar-menu li.active a").size() > 0) {
                $("ul.sidebar-menu li.active a").trigger("click");
            } else {
                $("ul.sidebar-menu li a[url!='javascript:;']:first").trigger("click");
            }

            //保留最后一次点击的窗口
            $(document).on("click", "a[addtabs]", function (e) {
            	if($(this).attr("url").indexOf('javascript:')<0)
            		Util.api.store("lastpage", $(this).attr("url"));
            });
            
            //回到最后一次打开的页面
           var lastpage = Util.api.get("lastpage");
            if (lastpage && lastpage.indexOf('javascript:')<0) {
                //刷新页面后跳到到刷新前的页面
                UtilBack.api.addtabs(lastpage);
            }

            /**
             * Toggles layout classes
             *
             * @param String cls the layout class to toggle
             * @returns void
             */
            function change_layout(cls) {
                $("body").toggleClass(cls);
                AdminLTE.layout.fixSidebar();
                //Fix the problem with right sidebar and layout boxed
                if (cls == "layout-boxed")
                    AdminLTE.controlSidebar._fix($(".control-sidebar-bg"));
                if ($('body').hasClass('fixed') && cls == 'fixed' && false) {
                    AdminLTE.pushMenu.expandOnHover();
                    AdminLTE.layout.activate();
                }
                AdminLTE.controlSidebar._fix($(".control-sidebar-bg"));
                AdminLTE.controlSidebar._fix($(".control-sidebar"));
            }

            setup();
            /**
             * Retrieve default settings and apply them to the template
             *
             * @returns void
             */
            function setup() {
                var tmp = Util.api.get('skin');
                if (tmp && $.inArray(tmp, my_skins) > -1)
                    Util.api.change_skin(tmp);

                // Add the change skin listener
                $("[data-skin]").on('click', function (e) {
                    if ($(this).hasClass('knob'))
                        return;
                    e.preventDefault();
                    Util.api.change_skin($(this).data('skin'));
                });

                // Add the layout manager
                $("[data-layout]").on('click', function () {
                    change_layout($(this).data('layout'));
                });

                $("[data-menu]").on('click', function () {
                    if ($(this).data("menu") == 'show-submenu') {
                        $("ul.sidebar-menu").toggleClass("show-submenu");
                    } else {
                        $(".nav-addtabs").toggleClass("disable-top-badge");
                    }
                });

                $("[data-controlsidebar]").on('click', function () {
                    change_layout($(this).data('controlsidebar'));
                    var slide = !AdminLTE.options.controlSidebarOptions.slide;
                    AdminLTE.options.controlSidebarOptions.slide = slide;
                    if (!slide)
                        $('.control-sidebar').removeClass('control-sidebar-open');
                });

                $("[data-sidebarskin='toggle']").on('click', function () {
                    var sidebar = $(".control-sidebar");
                    if (sidebar.hasClass("control-sidebar-dark")) {
                        sidebar.removeClass("control-sidebar-dark")
                        sidebar.addClass("control-sidebar-light")
                    } else {
                        sidebar.removeClass("control-sidebar-light")
                        sidebar.addClass("control-sidebar-dark")
                    }
                });

                $("[data-enable='expandOnHover']").on('click', function () {
                    $(this).attr('disabled', true);
                    AdminLTE.pushMenu.expandOnHover();
                    if (!$('body').hasClass('sidebar-collapse'))
                        $("[data-layout='sidebar-collapse']").click();
                });

                //  Reset options
                if ($('body').hasClass('fixed')) {
                    $("[data-layout='fixed']").attr('checked', 'checked');
                }
                if ($('body').hasClass('layout-boxed')) {
                    $("[data-layout='layout-boxed']").attr('checked', 'checked');
                }
                if ($('body').hasClass('sidebar-collapse')) {
                    $("[data-layout='sidebar-collapse']").attr('checked', 'checked');
                }
                if ($('ul.sidebar-menu').hasClass('show-submenu')) {
                    $("[data-menu='show-submenu']").attr('checked', 'checked');
                }
                if ($('ul.nav-addtabs').hasClass('disable-top-badge')) {
                    $("[data-menu='disable-top-badge']").attr('checked', 'checked');
                }

             // tab右键
                $('<div class="popup_menu app-menu"><ul><li menu="menu1">关闭当前标签</li><li menu="menu2">关闭左侧标签</li><li menu="menu3">关闭右侧标签</li><li menu="menu4">关闭其它标签</li><li menu="menu5">关闭全部标签</li></ul></div>')  
                .appendTo('body').hide();
                $(document).on('contextmenu', '[role="presentation"]', function(e) {
                	$('.popup_menu').css({left: e.clientX,top: e.clientY}).show();
                	$('.popup_menu').data('menu', $(this).attr('id'));
                    return false;
                }).on('click', function(){
                    $('.popup_menu').hide();
                });
                $(document).on('click', '[menu="menu1"]', function(e) {
                	$('#' + $('.popup_menu').data('menu')).find('.close-tab').trigger('click');
                }).on('click', '[menu="menu2"]', function(e) {
                	var r = true, t = $('.popup_menu').data('menu');
                	$('[role="presentation"]').each(function() {
                		var id = $(this).attr('id');
                		if(r && t != id) {
                			$(this).find('.close-tab').trigger('click');
                		} else if(t == id) {
                			r = false;
                		}
                	});
                }).on('click', '[menu="menu3"]', function(e) {
                	var r = false, t = $('.popup_menu').data('menu');
                	$('[role="presentation"]').each(function() {
                		var id = $(this).attr('id');
                		if(r && t != id) {
                			$(this).find('.close-tab').trigger('click');
                		} else if(t == id) {
                			r = true;
                		}
                	});
                }).on('click', '[menu="menu4"]', function(e) {
                	var t = $('.popup_menu').data('menu');
                	$('[role="presentation"]').each(function() {
                		var id = $(this).attr('id');
                		if(t != id) {
                			$(this).find('.close-tab').trigger('click');
                		}
                	});
                }).on('click', '[menu="menu5"]', function(e) {
                	$('[role="presentation"]').each(function() {
                		$(this).find('.close-tab').trigger('click');
                	});
                });
                
                $(document).ready(function(){
                    $('.main-sidebar').removeClass('hide');
                    $(".menuresult").width($("form.sidebar-form > .input-group").width());
                });
            }
            $(window).resize();
            return true;
        }
    };

    return Controller;
});